/*

  The contents of this file are subject to the Mozilla Public License Version
  1.1 (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at 
  
           http://www.mozilla.org/MPL/ 
  
  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  for the specific language governing rights and limitations under the License. 
  
  The Original Code is Tamina Framework.
  
  The Initial Developer of the Original Code is
  MOUTON David (aka damo)  <damo@tamina-online.com>.
  Portions created by the Initial Developer are Copyright (C) 2004-2007
  the Initial Developer. All Rights Reserved.
  
  Contributor(s) :
  
*/
package org.tamina.utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.utils.Dictionary;	
	import mx.utils.StringUtil;
	import flash.net.URLRequest;
	import flash.events.IOErrorEvent;

	public class PropertiesBundle extends EventDispatcher implements RessourceBundle
	{
		//Props
		private var _dataLoader:URLLoader;
		private var __name:String;
		private var __properties:Dictionary;
		
		
		//Constructeur
		public function PropertiesBundle(name:String):void{
			__name = name;
			__properties = new Dictionary();
		}

		//Methodes publiques
		public function loadRessource(path:String):void
		{
			trace("PropertiesBundle : debut ");
			var request:URLRequest = new URLRequest(path);
			_dataLoader = new URLLoader();
			_dataLoader.addEventListener(Event.COMPLETE,parseProperties);
			_dataLoader.addEventListener(IOErrorEvent.IO_ERROR, ioerror);
			_dataLoader.load(request);
		}
		
		public function getRessource(key:String):String
		{
			return (__properties[key] as String || " ");

		}
		
		public function getKeys():Array
		{
			var keys:Array = [];
			for(var z:String in __properties){
				keys.push(z);
			}
			return keys;
		}
		
		//Methodes privées
		private function ioerror(e:IOErrorEvent):void{
			trace("error io : " + e.text);
		}
		private function parseProperties(e:Event):void{
			trace("PropertiesBundle : chargement ok ");
			_dataLoader.removeEventListener(Event.COMPLETE,parseProperties);
			var entries:Array = String(_dataLoader.data).split("\r\n");
			var i:int = entries.length;
			while(--i > -1){
				var entry:String = entries[i];
				if(entry.charAt(0) != "#"){
					var index:int = entry.indexOf("=");
					var key:String = StringUtil.trim(entry.slice(0,index));
					var value:String = StringUtil.trim(entry.slice(index+1,entry.length));
					if (key.length > 0 && value.length > 0){
						__properties[key] = value;
					}
				}
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}		
	}
}